package com.shuguang.medicalcare;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PersonSet extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
    public TextView saveBtn;
    public Button back;
    public Switch bohaoAuto;
    public Switch bohaoR;

    public TextView jianButton;
    public TextView jiaButton;

    public TextView countT;

    public RadioGroup rg1;
    public RadioGroup rg2;

    public  TextView currentVersion;

    public TextView logOut;

    String apkPath;


//    {"appDialType":2,"isAutoDial":"0","countDownSeconds":"0","crmDialType":1,"isRefreshList":"0",}
    String appDialType;
    String isAutoDial;
    String countDownSeconds;
    String crmDialType;
    String isRefreshList;
    String callerId;

    private PersonSet.mHandler mhandler=new PersonSet.mHandler(this);

    private static class mHandler extends Handler {
        WeakReference<PersonSet> weakReference;
        public mHandler(PersonSet mainActivity){
            weakReference = new WeakReference<PersonSet>(mainActivity);
        }
        @Override
        public void handleMessage(Message msg){
            PersonSet mainActivity = weakReference.get();
            if(mainActivity != null){

                    if(msg.what == 3){
                        mainActivity.showUpdataDialog();
                    }else {
                        mainActivity.toast();
                    }



            }

        }

    }

    public void toast(){
        Toast.makeText(getApplicationContext(),"保存成功",Toast.LENGTH_SHORT).show();
        finish();

    }

    public void showUpdataDialog(){

        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(PersonSet.this);
        View dialogView = LayoutInflater.from(PersonSet.this)
                .inflate(R.layout.updata,null);

        customizeDialog.setView(dialogView);
        customizeDialog.setCancelable(false);

        AlertDialog alertDialog =  customizeDialog.show();

        Button downBtn = (Button) dialogView.findViewById(R.id.download);



        int max=100,min=1;
        int ran2 = (int) (Math.random()*(max-min)+min);

        int a= (int) new Date().getTime();




        String fileName= String.valueOf(ran2) + String.valueOf(a);
//        downBtn.setText(version);

        downBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Log.i("url+++", apkPath);
//                downBtn.setText(apkPath);
//                Toast.makeText(ListSelect.this, apkPath, Toast.LENGTH_SHORT).show();
//                apkPath







                new DownloadUtils(PersonSet.this,apkPath,"medicalCare"+fileName+".apk");

            }
        });





    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_set);

        try {
            test();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        init();
    }

    public  String toCover(String str){
        StringBuffer stringBuffer= new StringBuffer("");
        for(int i=0;i<str.length();i++){
            if(str.charAt(i) !='.'){
                stringBuffer.append(str.charAt(i));
            }
        }
        return  stringBuffer.toString();
    }

    public void test() throws PackageManager.NameNotFoundException {

        currentVersion=(TextView)findViewById(R.id.currentVersion) ;

        PackageManager pm =getApplicationContext().getPackageManager();
        PackageInfo pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);

        String versionName = pi.versionName;
        currentVersion.setText("v"+ versionName);
        int versioncode = pi.versionCode;


        (new Thread(){
            @Override
            public void run() {

                //实例化  里面可能会出现异常，需要try  catch
                OkHttpClient client = new OkHttpClient();

                String path= MedicalCareApi.newPath+"callcenter/checkVersion";


//            http://49.234.94.134:8081/ccapp/callcenter/checkVersion?type=6&now_version=1.0.0

//                        Request request = new Request.Builder().url(path).build();
                Request.Builder reqBuild = new Request.Builder();
                HttpUrl.Builder urlBuilder =HttpUrl.parse(path)
                        .newBuilder();
                urlBuilder.addQueryParameter("type", "6");
                urlBuilder.addQueryParameter("now_version", toCover(String.valueOf(versionName))  );

                Log.i("versionName", toCover(String.valueOf(versionName)));

                reqBuild.url(urlBuilder.build());
                Request request = reqBuild.build();



                try {

                    //Response是okhttp实例化，并且调用Request。执行后返回的结果
                    Response response = client.newCall(request).execute();
                    String s = response.body().string();//获取到的json数据
                    Log.i("path::", path);

                    JSONObject jsonObject =  new JSONObject(s);//转成json
                    int code = jsonObject.getInt("code");

//                    Log.i("jsonObject", String.valueOf(jsonObject.getInt("apk")) );
                    Log.i("版本号", s  );
                    if(code == 0){
//                                    无需更新




                    }

                    if(code == 1){

//                                    需要更新


                        Message msg = new Message();
                        msg.what=3;
                        mhandler.sendMessage(msg);

                        apkPath=jsonObject.getString("apk");

                        Log.i("apkName", apkPath);

                    }

                } catch (Exception e) {

                    e.printStackTrace();
                }




            }
        }).start();



    }

    public void init() {
        //        {"appDialType":2,"isAutoDial":"0","countDownSeconds":"0","crmDialType":1,"isRefreshList":"0",}
        SharedPreferences sp = getSharedPreferences("userinfo",MODE_PRIVATE);
//        app呼叫模式

        isAutoDial=   sp.getString("isAutoDial",""); // 0 1

        // Toast.makeText(PersonSet.this, isAutoDial, Toast.LENGTH_SHORT).show();

        isRefreshList=  sp.getString("isRefreshList",""); // 0 1
        countDownSeconds=  sp.getString("countDownSeconds","5"); // 5 - 10


        if(Integer.parseInt(countDownSeconds)< 5 || Integer.parseInt(countDownSeconds) >10){
            countDownSeconds ="5";
        }

        crmDialType= sp.getString("crmDialType","1"); // 1 2
        appDialType=  sp.getString("appDialType","1"); // 1  2
        callerId = sp.getString("callerId","");

        saveBtn=(TextView) findViewById(R.id.setBtn);
        back =(Button) findViewById(R.id.back);


        bohaoAuto=(Switch)findViewById(R.id.bohaoAuto) ;
        if(isAutoDial.equals("0")){
            bohaoAuto.setChecked(false);
        }else {
            bohaoAuto.setChecked(true);
        }

        bohaoAuto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
//                    Toast.makeText(PersonSet.this, "ss+"+ isAutoDial, Toast.LENGTH_SHORT).show();
                    isAutoDial="1";
                }else{
                    isAutoDial="0";
                }
            }
        });



        bohaoR=(Switch)findViewById(R.id.bohaoR);
        if(isRefreshList.equals("0")){
            bohaoR.setChecked(false);
        }else {
            bohaoR.setChecked(true);
        }
        bohaoR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    isRefreshList="1";
                }else{
                    isRefreshList="0";
                }
            }
        });

        countT=(TextView)findViewById(R.id.count);

        countT.setText(countDownSeconds);


        jianButton=(TextView)findViewById(R.id.jianButton);
        jianButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num= Integer.parseInt(countDownSeconds);
                if(num > 5){
                    countDownSeconds=String.valueOf(num-1);
                }else if(num ==5){
                    countDownSeconds="5";
                }

                countT.setText(countDownSeconds);
            }
        });


        jiaButton=(TextView)findViewById(R.id.jiaButton);
        jiaButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num= Integer.parseInt(countDownSeconds);
                if(num < 10){
                    countDownSeconds=String.valueOf(num+1);
                }else if(num ==10){
                    countDownSeconds="10";
                }

                countT.setText(countDownSeconds);

            }
        });

        rg1=(RadioGroup)findViewById(R.id.radiogroup1);
        RadioButton rb1= (RadioButton)findViewById(R.id.radiobutton1);
        RadioButton rb2= (RadioButton)findViewById(R.id.radiobutton2);

        if(crmDialType.equals("1")){
            rb1.setChecked(true);
        }else {
            rb2.setChecked(true);
        }


        rg2=(RadioGroup)findViewById(R.id.radiogroup2);
        RadioButton rb3= (RadioButton)findViewById(R.id.radiobutton3);
        RadioButton rb4= (RadioButton)findViewById(R.id.radiobutton4);

        if(appDialType.equals("1")){
            rb3.setChecked(true);
        }else {
            rb4.setChecked(true);
        }


        rg1.setOnCheckedChangeListener(this);
        rg2.setOnCheckedChangeListener(this);

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent it= new Intent(getApplicationContext(), ListSelect.class);
//                startActivity(it);
//                Toast.makeText(PersonSet.this, "设置成功", Toast.LENGTH_SHORT).show();
//                finish();
                SharedPreferences sp =getSharedPreferences("userinfo",MODE_PRIVATE);
                SharedPreferences.Editor ed = sp.edit();

                // Toast.makeText(PersonSet.this, "ss+"+ isAutoDial, Toast.LENGTH_SHORT).show();

                ed.putString("isAutoDial",isAutoDial);
                ed.putString("isRefreshList",isRefreshList);
                ed.putString("countDownSeconds",countDownSeconds);
                ed.putString("crmDialType",crmDialType);
                ed.putString("appDialType",appDialType);



                ed.commit();
                toRequest();



            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        logOut=(TextView)findViewById(R.id.logOut);
        logOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


//                Intent it= new Intent(getApplicationContext(),MainActivity.class);
//                startActivity(it);
//                finish();



                 sureLogout();

            }


        });




    }

    public void sureLogout(){




        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(PersonSet.this);
        View dialogView = LayoutInflater.from(PersonSet.this)
                .inflate(R.layout.sure_logout,null);

        customizeDialog.setView(dialogView);
//        customizeDialog.setCancelable(false);

        AlertDialog alertDialog =  customizeDialog.show();

        Button downBtn = (Button) dialogView.findViewById(R.id.sure);
        Button cancel =(Button) dialogView.findViewById(R.id.cancel);

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });


        downBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Log.i("url+++", apkPath);
//                downBtn.setText(apkPath);
//                Toast.makeText(PersonSet.this, "yes", Toast.LENGTH_SHORT).show();
//                apkPath
//                new DownloadUtils(ListSelect.this,apkPath,"abc.apk");
                        SharedPreferences userSp = getSharedPreferences("userinfo",MODE_PRIVATE);
        SharedPreferences.Editor ed= userSp.edit();
        ed.clear();
        ed.commit();

                        List<Activity> list =getAllActivitys();
                for(int i =0;i<list.size();i++){
                    list.get(i).finish();
                }
                alertDialog.dismiss();
                Intent it= new Intent(getApplicationContext(),Splash.class);
                startActivity(it);




            }
        });







    }

    public List<Activity> getAllActivitys(){
        List<Activity> list=new ArrayList<>();
        try {
            Class<?> activityThread=Class.forName("android.app.ActivityThread");
            Method currentActivityThread=activityThread.getDeclaredMethod("currentActivityThread");
            currentActivityThread.setAccessible(true);
            //获取主线程对象
            Object activityThreadObject=currentActivityThread.invoke(null);
            Field mActivitiesField = activityThread.getDeclaredField("mActivities");
            mActivitiesField.setAccessible(true);
            Map<Object,Object> mActivities = (Map<Object,Object>) mActivitiesField.get(activityThreadObject);
            for (Map.Entry<Object,Object> entry:mActivities.entrySet()){
                Object value = entry.getValue();
                Class<?> activityClientRecordClass = value.getClass();
                Field activityField = activityClientRecordClass.getDeclaredField("activity");
                activityField.setAccessible(true);
                Object o = activityField.get(value);
                list.add((Activity) o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }



    public void toRequest(){
//          /callcenter/UpdateSettings?isAutoDial=1&countDownSeconds=5&isRefreshList=1&crmDialType=1&appDialType=2&callerId=1
        (new Thread(){
            @Override
            public void run() {
                  OkHttpClient client = new OkHttpClient();
                        //建立一个Request  通过Builder方法.Url里面填的就是json网址.build创建
//                        /callcenter/UpdateSettings?isAutoDial=1&countDownSeconds=5&isRefreshList=1&crmDialType=1&appDialType=2&callerId=1
//                        String path="http://wxwork.gzsg.cn/wxwork/callcenter/UpdateSettings";
                          String path=MedicalCareApi.newPath +"callcenter/UpdateSettings";

                        Log.i("path::", path);
//                String appDialType;
//                String isAutoDial;
//                String countDownSeconds;
//                String crmDialType;
//                String isRefreshList;
//                String callerId;

//                        Request request = new Request.Builder().url(path).build();
                        Request.Builder reqBuild = new Request.Builder();
                        HttpUrl.Builder urlBuilder =HttpUrl.parse(path)
                                .newBuilder();
                        urlBuilder.addQueryParameter("appDialType", appDialType);
                        urlBuilder.addQueryParameter("isAutoDial", isAutoDial);
                        urlBuilder.addQueryParameter("countDownSeconds", countDownSeconds);
                        urlBuilder.addQueryParameter("crmDialType", crmDialType);
                        urlBuilder.addQueryParameter("isRefreshList", isRefreshList);
                        urlBuilder.addQueryParameter("callerId", callerId);

                        reqBuild.url(urlBuilder.build());
                        Request request = reqBuild.build();



                        try {

                            //Response是okhttp实例化，并且调用Request。执行后返回的结果
                            Response response = client.newCall(request).execute();
                            String s = response.body().string();//获取到的json数据

                            Log.i("保存信息::", s);
//                            JSONObject jsonObject =  new JSONObject(s);//转成json
//
//                            Integer code = (Integer)jsonObject.getInt("result");
//
//                            if(code == 0){}
//                            Toast.makeText(getApplicationContext(),"保存成功",Toast.LENGTH_SHORT).show();
                            Message msg=new Message();
                            mhandler.sendMessage(msg);


                        } catch (Exception e) {

                            e.printStackTrace();
                        }
            }
        }).start();

//
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch(checkedId){
            case R.id.radiobutton1:
//                Toast.makeText(PersonSet.this, "1", Toast.LENGTH_SHORT).show();
                crmDialType="1";
                break;
            case R.id.radiobutton2:
//                Toast.makeText(PersonSet.this, "2", Toast.LENGTH_SHORT).show();
                crmDialType="2";
                break;



            case R.id.radiobutton3:
//                Toast.makeText(PersonSet.this, "3", Toast.LENGTH_SHORT).show();
                appDialType="1";
                break;
            case R.id.radiobutton4:
//                Toast.makeText(PersonSet.this, "4", Toast.LENGTH_SHORT).show();
                appDialType="2";
                break;
        }
    }
}